/*
 * @Author: Kiro AI Assistant
 * @Date: 2025-01-10
 * @Description: 优化的音乐列表项组件 - 提升列表滚动性能
 */

import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../../models/music_item_model.dart';
import '../../viewmodels/music_player_view_model.dart';
import '../../utils/performance_monitor.dart';
import 'album_cover_widget.dart';

/// 优化的音乐列表项组件
/// 使用性能优化技术减少重建和提升滚动性能
class OptimizedMusicListItem extends StatefulWidget {
  /// 音乐数据
  final MusicItemModel music;

  /// 列表项索引
  final int index;

  /// 点击回调
  final VoidCallback? onTap;

  /// 添加到播放列表回调
  final VoidCallback? onAddToPlaylist;

  /// 是否显示索引
  final bool showIndex;

  /// 是否显示添加按钮
  final bool showAddButton;

  /// 是否显示播放状态指示器
  final bool showPlayingIndicator;

  /// 自定义高度
  final double? height;

  const OptimizedMusicListItem({
    super.key,
    required this.music,
    required this.index,
    this.onTap,
    this.onAddToPlaylist,
    this.showIndex = false,
    this.showAddButton = true,
    this.showPlayingIndicator = true,
    this.height,
  });

  @override
  State<OptimizedMusicListItem> createState() => _OptimizedMusicListItemState();
}

class _OptimizedMusicListItemState extends State<OptimizedMusicListItem>
    with AutomaticKeepAliveClientMixin {
  @override
  bool get wantKeepAlive => false; // 不保持状态，让系统自动回收

  @override
  Widget build(BuildContext context) {
    super.build(context); // 必须调用，用于 AutomaticKeepAliveClientMixin

    // 跟踪组件重建（仅在调试模式下）
    PerformanceMonitor.trackRebuild(
        'OptimizedMusicListItem[${widget.index}]', context);

    return Container(
      height: widget.height ?? 72,
      padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
      child: Row(
        children: [
          // 索引或专辑封面
          _buildLeadingWidget(),

          const SizedBox(width: 12),

          // 音乐信息
          Expanded(
            child: _buildMusicInfo(),
          ),

          // 播放状态指示器
          if (widget.showPlayingIndicator) _buildPlayingIndicator(),

          // 操作按钮
          _buildActionButtons(),
        ],
      ),
    );
  }

  /// 构建前导组件（索引或专辑封面）
  Widget _buildLeadingWidget() {
    if (widget.showIndex) {
      return Container(
        width: 40,
        height: 40,
        alignment: Alignment.center,
        child: Text(
          '${widget.index + 1}',
          style: TextStyle(
            fontSize: 16,
            fontWeight: FontWeight.bold,
            color: Colors.grey.shade600,
          ),
        ),
      );
    } else {
      return ThumbnailAlbumCoverWidget(
        music: widget.music,
        size: 56,
      );
    }
  }

  /// 构建音乐信息
  Widget _buildMusicInfo() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        // 歌曲标题
        Text(
          widget.music.title,
          style: const TextStyle(
            fontSize: 16,
            fontWeight: FontWeight.w500,
          ),
          maxLines: 1,
          overflow: TextOverflow.ellipsis,
        ),

        const SizedBox(height: 4),

        // 艺术家和专辑信息
        Text(
          '${widget.music.artist} • ${widget.music.album}',
          style: TextStyle(
            fontSize: 14,
            color: Colors.grey.shade600,
          ),
          maxLines: 1,
          overflow: TextOverflow.ellipsis,
        ),
      ],
    );
  }

  /// 构建播放状态指示器
  Widget _buildPlayingIndicator() {
    return Consumer<MusicPlayerViewModel>(
      builder: (context, viewModel, child) {
        final isCurrentPlaying = viewModel.currentTrack?.id == widget.music.id;

        if (!isCurrentPlaying) {
          return const SizedBox(width: 24); // 占位空间
        }

        return ValueListenableBuilder<bool>(
          valueListenable: viewModel.isPlaying,
          builder: (context, isPlaying, child) {
            return Container(
              width: 24,
              height: 24,
              margin: const EdgeInsets.only(right: 8),
              child: isPlaying
                  ? _buildPlayingAnimation()
                  : Icon(
                      Icons.pause,
                      size: 20,
                      color: Theme.of(context).primaryColor,
                    ),
            );
          },
        );
      },
    );
  }

  /// 构建播放动画
  Widget _buildPlayingAnimation() {
    return Icon(
      Icons.graphic_eq,
      size: 20,
      color: Theme.of(context).primaryColor,
    );
  }

  /// 构建操作按钮
  Widget _buildActionButtons() {
    return Row(
      mainAxisSize: MainAxisSize.min,
      children: [
        // 添加到播放列表按钮
        if (widget.showAddButton)
          IconButton(
            icon: const Icon(Icons.add, size: 20),
            onPressed: widget.onAddToPlaylist,
            constraints: const BoxConstraints(
              minWidth: 32,
              minHeight: 32,
            ),
            padding: EdgeInsets.zero,
            tooltip: '添加到播放列表',
          ),

        // 更多操作按钮
        IconButton(
          icon: const Icon(Icons.more_vert, size: 20),
          onPressed: () => _showMoreOptions(context),
          constraints: const BoxConstraints(
            minWidth: 32,
            minHeight: 32,
          ),
          padding: EdgeInsets.zero,
          tooltip: '更多选项',
        ),
      ],
    );
  }

  /// 显示更多选项菜单
  void _showMoreOptions(BuildContext context) {
    showModalBottomSheet(
      context: context,
      backgroundColor: Colors.transparent,
      builder: (context) => MusicItemOptionsSheet(
        music: widget.music,
        onPlayNext: () {
          final viewModel = context.read<MusicPlayerViewModel>();
          viewModel.addToPlaylist(widget.music);
          Navigator.of(context).pop();
          ScaffoldMessenger.of(context).showSnackBar(
            const SnackBar(content: Text('已添加到播放列表')),
          );
        },
        onPlayNow: () {
          final viewModel = context.read<MusicPlayerViewModel>();
          viewModel.play(widget.music);
          Navigator.of(context).pop();
        },
      ),
    );
  }
}

/// 音乐项选项面板
class MusicItemOptionsSheet extends StatelessWidget {
  final MusicItemModel music;
  final VoidCallback? onPlayNext;
  final VoidCallback? onPlayNow;

  const MusicItemOptionsSheet({
    super.key,
    required this.music,
    this.onPlayNext,
    this.onPlayNow,
  });

  @override
  Widget build(BuildContext context) {
    return Container(
      decoration: const BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.vertical(top: Radius.circular(20)),
      ),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          // 拖拽指示器
          Container(
            width: 40,
            height: 4,
            margin: const EdgeInsets.symmetric(vertical: 12),
            decoration: BoxDecoration(
              color: Colors.grey.shade300,
              borderRadius: BorderRadius.circular(2),
            ),
          ),

          // 音乐信息
          Padding(
            padding: const EdgeInsets.all(16),
            child: Row(
              children: [
                ThumbnailAlbumCoverWidget(
                  music: music,
                  size: 60,
                ),
                const SizedBox(width: 12),
                Expanded(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        music.title,
                        style: const TextStyle(
                          fontSize: 16,
                          fontWeight: FontWeight.bold,
                        ),
                        maxLines: 1,
                        overflow: TextOverflow.ellipsis,
                      ),
                      Text(
                        music.artist,
                        style: TextStyle(
                          fontSize: 14,
                          color: Colors.grey.shade600,
                        ),
                        maxLines: 1,
                        overflow: TextOverflow.ellipsis,
                      ),
                    ],
                  ),
                ),
              ],
            ),
          ),

          // 操作选项
          Column(
            children: [
              ListTile(
                leading: const Icon(Icons.play_arrow),
                title: const Text('立即播放'),
                onTap: onPlayNow,
              ),
              ListTile(
                leading: const Icon(Icons.queue_music),
                title: const Text('添加到播放列表'),
                onTap: onPlayNext,
              ),
              ListTile(
                leading: const Icon(Icons.share),
                title: const Text('分享'),
                onTap: () {
                  Navigator.of(context).pop();
                  // TODO: 实现分享功能
                  ScaffoldMessenger.of(context).showSnackBar(
                    const SnackBar(content: Text('分享功能待实现')),
                  );
                },
              ),
            ],
          ),

          // 底部安全区域
          SizedBox(height: MediaQuery.of(context).padding.bottom),
        ],
      ),
    );
  }
}

/// 紧凑版音乐列表项
/// 适用于空间有限的场景
class CompactMusicListItem extends StatelessWidget {
  final MusicItemModel music;
  final int index;
  final VoidCallback? onTap;
  final bool showIndex;

  const CompactMusicListItem({
    super.key,
    required this.music,
    required this.index,
    this.onTap,
    this.showIndex = false,
  });

  @override
  Widget build(BuildContext context) {
    return InkWell(
      onTap: onTap,
      child: Container(
        height: 56,
        padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
        child: Row(
          children: [
            // 索引或小封面
            if (showIndex)
              Container(
                width: 32,
                alignment: Alignment.center,
                child: Text(
                  '${index + 1}',
                  style: TextStyle(
                    fontSize: 14,
                    color: Colors.grey.shade600,
                  ),
                ),
              )
            else
              ThumbnailAlbumCoverWidget(
                music: music,
                size: 40,
              ),

            const SizedBox(width: 12),

            // 音乐信息
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Text(
                    music.title,
                    style: const TextStyle(
                      fontSize: 14,
                      fontWeight: FontWeight.w500,
                    ),
                    maxLines: 1,
                    overflow: TextOverflow.ellipsis,
                  ),
                  Text(
                    music.artist,
                    style: TextStyle(
                      fontSize: 12,
                      color: Colors.grey.shade600,
                    ),
                    maxLines: 1,
                    overflow: TextOverflow.ellipsis,
                  ),
                ],
              ),
            ),

            // 播放状态指示器
            Consumer<MusicPlayerViewModel>(
              builder: (context, viewModel, child) {
                final isCurrentPlaying = viewModel.currentTrack?.id == music.id;

                if (isCurrentPlaying) {
                  return ValueListenableBuilder<bool>(
                    valueListenable: viewModel.isPlaying,
                    builder: (context, isPlaying, child) {
                      return Icon(
                        isPlaying ? Icons.graphic_eq : Icons.pause,
                        size: 16,
                        color: Theme.of(context).primaryColor,
                      );
                    },
                  );
                }

                return const SizedBox(width: 16);
              },
            ),
          ],
        ),
      ),
    );
  }
}
